import React, { useState, useCallback, useRef } from 'react';
import { Layout, Card, Button, Space, message, Modal, Input, Select } from 'antd';
import { 
  PlusOutlined, 
  SaveOutlined, 
  EyeOutlined, 
  CodeOutlined,
  UndoOutlined,
  RedoOutlined,
  DeleteOutlined,
  CopyOutlined,
  SettingOutlined
} from '@ant-design/icons';
import ComponentPanel from '../components/designer/ComponentPanel';
import Canvas from '../components/designer/Canvas';
import PropertyPanel from '../components/designer/PropertyPanel';
import StructureTree from '../components/designer/StructureTree';
import DataSourcePanel from '../components/designer/DataSourcePanel';
import { useApp } from '../context/AppContext.jsx';
import './DesignerPage.jd.css';
import { arrayMove } from '@dnd-kit/sortable'; // 引入arrayMove

const { Sider, Content } = Layout;

// 结构性克隆函数，保持 id 不变
function cloneComponents(components) {
  return components.map(comp => ({
    ...comp,
    children: comp.children ? cloneComponents(comp.children) : undefined
  }));
}

// 辅助函数：根据路径查找组件
const findComponentByPath = (components, path) => {
  let current = components;
  let component = null;
  for (let i = 0; i < path.length; i++) {
    const index = path[i];
    if (!current || index === undefined || index >= current.length) {
      return null; // 路径无效
    }
    component = current[index];
    if (i < path.length - 1) {
      current = component.children;
    }
  }
  return component;
};

// 辅助函数：根据路径更新组件属性 (Immutability-friendly)
const updateComponentByPath = (components, path, updatedProps) => {
  if (!path || path.length === 0) return components; // 根组件或无效路径

  const newComponents = JSON.parse(JSON.stringify(components)); // Deep copy to ensure immutability
  let current = newComponents;

  for (let i = 0; i < path.length; i++) {
    const index = path[i];
    if (index === undefined || index >= current.length) {
      return components; // 路径无效
    }

    if (i === path.length - 1) {
      // 找到目标组件，更新其属性
      current[index] = { ...current[index], ...updatedProps };
    } else {
      // 遍历到父级，确保children是新的数组以保持不变性
      current[index] = { ...current[index], children: [...(current[index].children || [])] };
      current = current[index].children;
    }
  }
  return newComponents;
};

// 辅助函数：根据路径删除组件 (Immutability-friendly)
const deleteComponentByPath = (components, path) => {
  if (!path || path.length === 0) return components; // 无法删除根画布或无效路径

  const newComponents = JSON.parse(JSON.stringify(components)); // Deep copy
  if (path.length === 1) {
    return newComponents.filter((_, i) => i !== path[0]);
  }

  let current = newComponents;
  for (let i = 0; i < path.length - 1; i++) {
    const index = path[i];
    if (index === undefined || index >= current.length || !current[index].children) {
      return components; // 路径无效或没有children
    }
    current[index] = { ...current[index], children: [...current[index].children] }; // 确保children是新的数组
    current = current[index].children;
  }

  const lastIndex = path[path.length - 1];
  if (lastIndex !== undefined && lastIndex < current.length) {
    current.splice(lastIndex, 1);
  }
  return newComponents;
};

// 辅助函数：根据路径复制组件 (Immutability-friendly)
const copyComponentByPath = (components, path) => {
  if (!path || path.length === 0) return components; // 无法复制根画布或无效路径

  const componentToCopy = findComponentByPath(components, path);
  if (!componentToCopy) return components;

  // 创建一个深度复制的新组件，并生成新的ID
  const newComponent = JSON.parse(JSON.stringify(componentToCopy));
  newComponent.id = `component_${Date.now()}_copy`;
  // 遍历所有子组件，也更新它们的ID，确保完全独立
  const updateIds = (comp) => {
    comp.id = `component_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
    if (comp.children) {
      comp.children.forEach(updateIds);
    }
  };
  updateIds(newComponent);

  const newComponents = JSON.parse(JSON.stringify(components)); // Deep copy
  if (path.length === 1) {
    // 复制到根层级
    newComponents.splice(path[0] + 1, 0, newComponent);
    return newComponents;
  }

  let current = newComponents;
  for (let i = 0; i < path.length - 1; i++) {
    const index = path[i];
    if (index === undefined || index >= current.length || !current[index].children) {
      return components; // 路径无效或没有children
    }
    current[index] = { ...current[index], children: [...current[index].children] };
    current = current[index].children;
  }

  const parentIndex = path[path.length - 1]; // This should be the index in the parent's children array
  if (parentIndex !== undefined && parentIndex < current.length) { // This condition is problematic if path is not of length 1
    // Correct logic for inserting at the same level as the original component
    const targetParent = findComponentByPath(newComponents, path.slice(0, -1));
    if (targetParent) {
      if (!targetParent.children) {
        targetParent.children = [];
      }
      const insertIndex = path[path.length - 1];
      targetParent.children.splice(insertIndex + 1, 0, newComponent);
    } else { // Root level
      newComponents.splice(path[0] + 1, 0, newComponent);
    }
  }

  return newComponents;
};

// 辅助函数：在组件树中查找指定 id 的 path
function findPathById(components, id, currentPath = []) {
  for (let i = 0; i < components.length; i++) {
    const comp = components[i];
    if (comp.id === id) {
      console.log('findPathById: found', id, 'at', [...currentPath, i]);
      return [...currentPath, i];
    }
    if (comp.children) {
      const childPath = findPathById(comp.children, id, [...currentPath, i]);
      if (childPath) return childPath;
    }
  }
  return null;
}

// ====== 预置模板数据 ======
const simpleFormTemplate = [
  {
    id: 'component_1',
    type: 'text',
    label: '标题',
    props: { content: '用户注册', fontSize: 24, color: '#222' },
    style: { position: 'absolute', left: 40, top: 30 }
  },
  {
    id: 'component_2',
    type: 'input',
    label: '用户名',
    props: { placeholder: '请输入用户名' },
    style: { position: 'absolute', left: 40, top: 80, width: 260 }
  },
  {
    id: 'component_3',
    type: 'input',
    label: '密码',
    props: { placeholder: '请输入密码', inputType: 'password' },
    style: { position: 'absolute', left: 40, top: 130, width: 260 }
  },
  {
    id: 'component_4',
    type: 'button',
    label: '注册',
    props: { text: '注册', type: 'primary' },
    style: { position: 'absolute', left: 40, top: 190, width: 260 }
  }
];

const dashboardTemplate = [
  {
    id: 'component_1',
    type: 'text',
    label: '标题',
    props: { content: '销售数据看板', fontSize: 24, color: '#222' },
    style: { position: 'absolute', left: 40, top: 30 }
  },
  {
    id: 'component_2',
    type: 'chart',
    label: '图表',
    props: {},
    style: { position: 'absolute', left: 40, top: 80, width: 400, height: 300 }
  },
  {
    id: 'component_3',
    type: 'table',
    label: '表格',
    props: {},
    style: { position: 'absolute', left: 460, top: 80, width: 400, height: 300 }
  }
];

const cardTemplate = [
  {
    id: 'component_1',
    type: 'image',
    label: '图片',
    props: { src: 'https://via.placeholder.com/200x150' },
    style: { position: 'absolute', left: 40, top: 40, width: 200, height: 150 }
  },
  {
    id: 'component_2',
    type: 'text',
    label: '标题',
    props: { content: '产品名称', fontSize: 20, color: '#1677ff' },
    style: { position: 'absolute', left: 260, top: 50 }
  },
  {
    id: 'component_3',
    type: 'text',
    label: '描述',
    props: { content: '这里是产品的简要描述。', fontSize: 14, color: '#666' },
    style: { position: 'absolute', left: 260, top: 90 }
  },
  {
    id: 'component_4',
    type: 'button',
    label: '操作',
    props: { text: '立即购买', type: 'primary' },
    style: { position: 'absolute', left: 260, top: 140 }
  }
];
// ====== 预置模板数据 END ======

export default function DesignerPage() {
  const { canvas, setCanvas } = useApp();
  const [undoStack, setUndoStack] = useState([]); // 撤销栈，存 {canvas, selectedPath}
  const [selectedPath, setSelectedPath] = useState(null); // 选中路径
  const [collapsed, setCollapsed] = useState(false);
  const [activePanel, setActivePanel] = useState('components');
  const [pageName, setPageName] = useState('新页面');
  const [previewVisible, setPreviewVisible] = useState(false);
  const moveDebounceRef = useRef(null);
  const lastMoveSnapshotRef = useRef(null);

  // 封装 setCanvas，带撤销
  const setCanvasWithUndo = (updater) => {
    setCanvas(prevCanvas => {
      const nextCanvas = typeof updater === 'function' ? updater(prevCanvas) : updater;
      if (JSON.stringify(prevCanvas) !== JSON.stringify(nextCanvas)) {
        setUndoStack(prev => [...prev, { canvas: prevCanvas, selectedPath }]);
      }
      return nextCanvas;
    });
  };

  // 添加组件到画布
  const handleAddComponent = useCallback((component) => {
    const newComponent = {
      ...component,
      id: `component_${Date.now()}`,
      props: { ...component.defaultProps },
      style: {
        ...component.defaultStyle,
        position: 'absolute',
        left: 40 * canvas.length,
        top: 40 * canvas.length,
      },
      children: component.type === 'container' || component.type === 'row' || component.type === 'col' ? [] : undefined, // 容器类组件有children
    };
    setCanvasWithUndo(prev => [...prev, newComponent]);
    setSelectedPath([canvas.length]); // 选中新添加的组件
    message.success(`已添加 ${component.label}`);
  }, [canvas, setCanvasWithUndo]);

  // 删除组件
  const handleDeleteComponent = useCallback(() => {
    if (selectedPath !== null) {
      setCanvasWithUndo(prev => deleteComponentByPath(prev, selectedPath));
      setSelectedPath(null);
      message.success('组件已删除');
    }
  }, [selectedPath, setCanvasWithUndo]);

  // 复制组件
  const handleCopyComponent = useCallback(() => {
    if (selectedPath !== null) {
      setCanvasWithUndo(prev => copyComponentByPath(prev, selectedPath));
      message.success('组件已复制');
    }
  }, [selectedPath, setCanvasWithUndo]);

  // 保存页面
  const handleSave = useCallback(() => {
    const pageData = {
      name: pageName,
      components: canvas, // canvas现在是树形结构
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    localStorage.setItem('pageData', JSON.stringify(pageData));
    message.success('页面已保存');
  }, [canvas, pageName]);

  // 预览页面
  const handlePreview = useCallback(() => {
    setPreviewVisible(true);
  }, []);

  // 获取当前选中组件
  const selectedComponent = selectedPath ? findComponentByPath(canvas, selectedPath) : null;

  // 更新选中组件的属性
  const handleUpdateComponent = useCallback((updatedProps) => {
    if (selectedPath) {
      setCanvasWithUndo(prev => updateComponentByPath(prev, selectedPath, updatedProps));
    }
  }, [selectedPath, setCanvasWithUndo]);

  // 核心拖拽逻辑处理
  const handleComponentDragEnd = useCallback((event) => {
    const { active, over } = event;

    // 拖拽前记录当前选中组件的 id
    const selectedId = selectedPath ? findComponentByPath(canvas, selectedPath)?.id : null;

    if (!over) { 
      setCanvasWithUndo(canvas);
      return;
    }

    const activeId = active.id;
    const overId = over.id;
    const isNewComponentDrag = active.data.current && active.data.current.type === 'newComponent';

    if (!isNewComponentDrag && activeId === overId) return; // 拖拽现有组件到自身

    let componentToMove = null;
    let activeComponentPath = null; 
    let overComponentPath = null; 
    let overContainerPath = null; 

    const newCanvas = cloneComponents(canvas); // 结构性克隆，保持 id 不变

    if (isNewComponentDrag) {
      componentToMove = {
        ...active.data.current.componentData,
        id: `component_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`, // 为新组件生成唯一ID
        children: (active.data.current.componentData.type === 'container' || active.data.current.componentData.type === 'row' || active.data.current.componentData.type === 'col') ? [] : undefined,
      };
      // 对于新组件拖拽，不需要从canvas中移除
    } else { 
      // 查找并移除现有组件
      const traverseAndFindPaths = (comps, currentPath = []) => {
        for (let i = 0; i < comps.length; i++) {
          const comp = comps[i];
          const newPath = [...currentPath, i];
          if (comp.id === activeId) {
            activeComponentPath = newPath;
          }
          // overId可能是组件ID，也可能是droppable容器的ID (e.g., 'droppable-component_xyz')
          if (over.data.current && over.data.current.isContainer && over.data.current.componentId === comp.id) {
              overContainerPath = newPath;
          } else if (comp.id === overId) { 
              overComponentPath = newPath;
          }

          if (comp.children) {
            traverseAndFindPaths(comp.children, newPath);
          }
          if (activeComponentPath && (overComponentPath || overContainerPath)) return; // Short-circuit if paths are found
        }
      };
      traverseAndFindPaths(newCanvas); // Search in the mutable newCanvas

      if (!activeComponentPath) {
        console.warn("Active component path not found for existing component.", activeId);
        setCanvasWithUndo(canvas); // Revert
        return;
      }

      let activeParentRef = newCanvas; // Reference to the parent array where activeComponent is
      if (activeComponentPath.length > 1) {
        activeParentRef = findComponentByPath(newCanvas, activeComponentPath.slice(0, -1)).children; // Get mutable children array
      }
      const activeIndex = activeComponentPath[activeComponentPath.length - 1];
      componentToMove = activeParentRef.splice(activeIndex, 1)[0]; // Remove and get the component

      if (!componentToMove) {
          console.error("Component to move not found after removal (existing component).");
          setCanvasWithUndo(canvas); // Revert to previous valid state
          return;
      }
    }

    // Find paths for over target (component or container) in the potentially modified newCanvas
    if (!isNewComponentDrag) { // Only search for over paths if not a new component drag (active and over ids are available)
      let tempOverComponentPath = null;
      let tempOverContainerPath = null;
      const traverseAndFindOverPaths = (comps, currentPath = []) => {
        for (let i = 0; i < comps.length; i++) {
          const comp = comps[i];
          const newPath = [...currentPath, i];
          if (over.data.current && over.data.current.isContainer && over.data.current.componentId === comp.id) {
              tempOverContainerPath = newPath;
          } else if (comp.id === overId) { 
              tempOverComponentPath = newPath;
          }
          if (comp.children) {
            traverseAndFindOverPaths(comp.children, newPath);
          }
          if (tempOverComponentPath || tempOverContainerPath) return;
        }
      };
      traverseAndFindOverPaths(newCanvas); // Search in the modified newCanvas for over target
      overComponentPath = tempOverComponentPath;
      overContainerPath = tempOverContainerPath;
    }

    // --- Determine insertion target and position, then insert ---
    let targetComponentsArray = null; // The array where the component will be inserted
    let insertIndex = -1; // The index within that array
    let targetPath = []; // The path to the new component after insertion

    if (overContainerPath) { // Case A: Dropped directly onto a container's droppable area
      const targetContainer = findComponentByPath(newCanvas, overContainerPath);
      if (!targetContainer) {
        console.error("Target container not found for droppable ID.");
        setCanvasWithUndo(canvas); 
        return;
      }
      if (!targetContainer.children) {
        targetContainer.children = []; 
      }
      targetComponentsArray = targetContainer.children;
      insertIndex = targetComponentsArray.length; // Add to end of container's children
      targetPath = [...overContainerPath, insertIndex];
      message.success(`组件已添加到 ${targetContainer.label} 容器`);

    } else if (overComponentPath) { // Case B: Dropped onto another component (sibling reorder)
      const overParentPath = overComponentPath.slice(0, -1);
      const overIndex = overComponentPath[overComponentPath.length - 1];

      let overParentRef = newCanvas; 
      if (overParentPath.length > 0) {
        const tempOverParent = findComponentByPath(newCanvas, overParentPath);
        if (tempOverParent && tempOverParent.children) {
          overParentRef = tempOverParent.children; 
        } else {
            console.error("Over component's parent not found or has no children.");
            setCanvasWithUndo(canvas); 
            return;
        }
      }
      
      targetComponentsArray = overParentRef;
      insertIndex = overIndex; // Insert before the over component
      targetPath = [...overParentPath, insertIndex];
      message.success("组件已重新排序");

    } else { // Case C: Dropped onto the root canvas's blank area (no specific over component or container)
      targetComponentsArray = newCanvas;
      insertIndex = targetComponentsArray.length; // Add to end of root canvas
      targetPath = [insertIndex];
      message.success("组件已添加到画布根目录");
    }

    // --- Perform insertion (if target and index are valid) ---
    if (targetComponentsArray && insertIndex !== -1) {
        // 拖拽到空白区或最后一个组件下方，插入到末尾
        if (!over && !overComponentPath && !overContainerPath) {
          insertIndex = targetComponentsArray.length;
        } else if (overComponentPath && insertIndex === targetComponentsArray.length - 1 && overId === targetComponentsArray[targetComponentsArray.length - 1]?.id) {
          // 拖拽到最后一个组件，判断鼠标是否在下半部分
          if (event && event.over && event.over.rect && event.activatorEvent && event.activatorEvent.clientY) {
            const overRect = event.over.rect;
            const clientY = event.activatorEvent.clientY;
            console.log('拖拽到最后一个组件:', { overRect, clientY, insertIndex });
            if (clientY > overRect.top + overRect.height / 2) {
              insertIndex = targetComponentsArray.length;
              console.log('插入到末尾:', insertIndex);
            }
          }
        }
        // 拖拽到自己下方或同一位置时不做任何操作
        if (!isNewComponentDrag && activeComponentPath && overComponentPath && JSON.stringify(activeComponentPath) === JSON.stringify(overComponentPath)) {
          setCanvasWithUndo(canvas);
          setSelectedPath(selectedPath);
          return;
        }
        // 只有同一父级内移动，且 activeIndex < insertIndex 且 insertIndex < arr.length 时，insertIndex--
        if (
          !isNewComponentDrag &&
          activeComponentPath &&
          overComponentPath &&
          JSON.stringify(activeComponentPath.slice(0, -1)) === JSON.stringify(overComponentPath.slice(0, -1))
        ) {
          const activeIndex = activeComponentPath[activeComponentPath.length - 1];
          if (activeIndex < insertIndex && insertIndex < targetComponentsArray.length) {
            insertIndex = insertIndex - 1;
          }
        }
        // 拖到末尾时，insertIndex 应等于目标数组长度
        if (insertIndex > targetComponentsArray.length) {
          insertIndex = targetComponentsArray.length;
        }
        targetComponentsArray.splice(insertIndex, 0, componentToMove);
        setCanvasWithUndo(() => newCanvas); // Update the main canvas state with the new tree
        // 拖拽后，用拖拽前记录的 selectedId 查找新 path
        if (selectedId) {
          const newPath = findPathById(newCanvas, selectedId);
          setSelectedPath(newPath);
        } else {
          setSelectedPath(null);
        }
    } else {
        setCanvasWithUndo(canvas); // Revert if insertion failed or logic path was not fully handled
        setSelectedPath(null);
    }

    if (!isNewComponentDrag && activeComponentPath && overComponentPath) {
      // 只处理同一父级内的拖拽
      if (JSON.stringify(activeComponentPath.slice(0, -1)) === JSON.stringify(overComponentPath.slice(0, -1))) {
        const activeIndex = activeComponentPath[activeComponentPath.length - 1];
        let moved = null;
        // 删除原位置
        moved = targetComponentsArray.splice(activeIndex, 1)[0];
        // 如果 activeIndex < insertIndex，插入前 insertIndex--
        if (activeIndex < insertIndex) {
          insertIndex--;
        }
        // 插入新位置
        targetComponentsArray.splice(insertIndex, 0, moved);
        setCanvasWithUndo(() => newCanvas);
        // 拖拽后，用拖拽前记录的 selectedId 查找新 path
        if (selectedId) {
          const newPath = findPathById(newCanvas, selectedId);
          setSelectedPath(newPath);
        } else {
          setSelectedPath(null);
        }
        return;
      }
    }

    // 只有真正变更才 push
    if (JSON.stringify(newCanvas) !== JSON.stringify(canvas)) {
      // 记录本次移动后的快照
      lastMoveSnapshotRef.current = newCanvas;
      // 清除上一个定时器
      if (moveDebounceRef.current) clearTimeout(moveDebounceRef.current);
      // 启动新定时器
      moveDebounceRef.current = setTimeout(() => {
        setCanvasWithUndo(() => lastMoveSnapshotRef.current);
        lastMoveSnapshotRef.current = null;
      }, 500); // 500ms防抖
      // 立即更新画布
      setCanvas(() => newCanvas);
    }

  }, [canvas, setCanvasWithUndo, setCanvas]);

  // 包装 setSelectedPath 加 log
  const handleSelect = (path) => {
    console.log('setSelectedPath', path);
    setSelectedPath(path);
  };

  // 撤销操作
  const handleUndo = useCallback(() => {
    setUndoStack(prev => {
      if (prev.length <= 1) return prev; // 只剩一个快照时不再撤销
      const last = prev[prev.length - 1];
      setCanvas(last.canvas);
      // 检查 selectedPath 是否还存在于 canvas
      const exists = last.selectedPath && findComponentByPath(last.canvas, last.selectedPath);
      setSelectedPath(exists ? last.selectedPath : null);
      return prev.slice(0, -1);
    });
  }, [setCanvas, setSelectedPath]);

  return (
    <div className="designer-root">
      {/* 顶部导航栏 */}
      <div className="designer-navbar">
        <div className="designer-navbar-left">低代码平台</div>
        <div className="designer-navbar-center">页面设计器</div>
        <div className="designer-navbar-right">
          {/* 预留用户信息、返回首页等 */}
        </div>
      </div>
      <div className="designer-main">
        {/* 左侧面板 */}
        <div className="designer-sider">
          <div className="designer-sider-tabs">
            <Button
              type={activePanel === 'components' ? 'primary' : 'default'}
              size="small"
              className={activePanel === 'components' ? 'designer-tab-active' : ''}
              onClick={() => setActivePanel('components')}
            >
              组件
            </Button>
            <Button
              type={activePanel === 'data' ? 'primary' : 'default'}
              size="small"
              className={activePanel === 'data' ? 'designer-tab-active' : ''}
              onClick={() => setActivePanel('data')}
            >
              数据
            </Button>
            <Button
              type={activePanel === 'structure' ? 'primary' : 'default'}
              size="small"
              className={activePanel === 'structure' ? 'designer-tab-active' : ''}
              onClick={() => setActivePanel('structure')}
            >
              结构
            </Button>
          </div>
          <div className="designer-sider-panel">
            {activePanel === 'components' && (
              <ComponentPanel onAddComponent={handleAddComponent} />
            )}
            {activePanel === 'data' && <DataSourcePanel />}
            {activePanel === 'structure' && (
              <StructureTree 
                components={canvas}
                selectedPath={selectedPath} // 传入selectedPath
                onSelect={setSelectedPath} // 传入setSelectedPath
              />
            )}
          </div>
        </div>
        {/* 中间画布区 */}
        <div className="designer-content">
          <div className="designer-toolbar">
            <Input
              placeholder="页面名称"
              value={pageName}
              onChange={(e) => setPageName(e.target.value)}
              className="designer-page-name"
            />
            <div className="designer-toolbar-btns">
              <Select
                style={{ width: 120, marginRight: 8 }}
                placeholder="选择模板"
                onSelect={val => {
                  if (val === 'form') setCanvasWithUndo(() => simpleFormTemplate);
                  if (val === 'dashboard') setCanvasWithUndo(() => dashboardTemplate);
                  if (val === 'card') setCanvasWithUndo(() => cardTemplate);
                }}
                options={[
                  { label: '简约表单', value: 'form' },
                  { label: '数据看板', value: 'dashboard' },
                  { label: '信息卡片', value: 'card' },
                ]}
              />
              <Button icon={<SaveOutlined />} onClick={handleSave}>保存</Button>
              <Button icon={<EyeOutlined />} onClick={handlePreview}>预览</Button>
              <Button icon={<CodeOutlined />}>导出</Button>
              <Button icon={<UndoOutlined />} onClick={handleUndo} disabled={undoStack.length <= 1}>撤销</Button>
              <Button icon={<RedoOutlined />} disabled>重做</Button>
              <Button 
                icon={<DeleteOutlined />} 
                danger 
                disabled={selectedPath === null}
                onClick={handleDeleteComponent}
              >删除</Button>
              <Button 
                icon={<CopyOutlined />} 
                disabled={selectedPath === null}
                onClick={handleCopyComponent}
              >复制</Button>
            </div>
          </div>
          <div className="designer-canvas-wrapper">
            {console.log('Canvas props selectedPath', selectedPath)}
            <Canvas 
              components={canvas}
              selectedPath={selectedPath}
              onSelect={handleSelect}
              onComponentDragEnd={handleComponentDragEnd} // 传递拖拽事件处理函数
            />
          </div>
        </div>
        {/* 右侧属性面板 */}
        <div className="designer-sider designer-sider-right">
          <PropertyPanel 
            component={selectedComponent}
            onUpdate={handleUpdateComponent} // 使用新的handleUpdateComponent
          />
        </div>
      </div>

      {/* 预览弹窗 */}
      <Modal
        title="页面预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width="80%"
        style={{ top: 20 }}
      >
        <div style={{ 
          minHeight: 600, 
          border: '1px solid #e5e6eb', 
          borderRadius: 8,
          padding: 20,
          background: '#fff',
          position: 'relative', // 关键，确保绝对定位子元素以此为参考
          overflow: 'auto'
        }}>
          {console.log('DesignerPage 预览弹窗 canvas', canvas, 'previewVisible', previewVisible)}
          <Canvas 
            components={canvas}
            preview={true}
          />
        </div>
      </Modal>
    </div>
  );
} 